<?php

require_once(getShopBasePath() . 'modules/klarna/api/kreditor.php');

/**
 * This class enables system updates without the need to empty the DB. It is ment not only to upgrade from one
 * version to another but also in leaps, like from version 1.03 to version 1.06. Which means that the updates
 * in version 1.01 and 1.02 shall not be applied.
 *
 * REMEMBER! IF YOU ALTER A TABLE AND ADDS A COLUMN, THE USER MUST! EMPTY THE TMP FOLDER AS ALL FILES A CASHED.
 *
 * Inspired by oxCountry
 *
 * @author Klarna
 */
class klarnaUpdater extends oxI18n {

	private $kutil = null;
	private $oDB = null;
	private $shopId = null;
	protected $currenciesToAdd = array(
										'SEK' => 0,
										'NOK' => 0,
										'DKK' => 0,
										);

	/**
	 * Makes a check if there is a need to update the system.
	 * It checks the version saved in the DB against the version in the kreditor.php file.
	 *
	 * This method also takes in consideration if the module is installed in the first place. If it isnt
	 * then it will return false and the system will use KlarnaInstall.php instead.
	 */
	public function checkIfUpdateIsNeeded() {
		$myConfig  = $this->getConfig();
		$shopid = $myConfig->getShopId();
		$oDB = oxDb::getDb(true);

		//Checks if there is anything installed at all, if no, then dont update, just install it.
		$sql = "SELECT OXID FROM klarnaconfig WHERE OXID = '" . $shopid . "';";
		$oxid = $oDB->getOne($sql);
		if(!$oxid) {
			return false;
		}

		//If a previous version is installed then check if it needs an update.
		$sql = "SELECT CURRVERSION FROM klarnaconfig WHERE OXID = '" . $shopid . "';";
		$currSysVersion = $oDB->getOne($sql);

		if(!$this->kutil) {
			$this->kutil = oxNew('klarnautil');
		}

		$installationVersion = $this->kutil->getKredVersion();
		return $currSysVersion != $installationVersion ? true : false;
	}

	/**
	 * This is the controller of the updating process.
	 * By using the switch case the system will update from the version they have now and up only.
	 */
	public function doUpdate() {
		$myConfig  = $this->getConfig();
		$shopid = $myConfig->getShopId();
		$oDB = oxDb::getDb(true);
		$sql = "SELECT CURRVERSION FROM klarnaconfig WHERE OXID = '" . $shopid . "';";
		$currSysVersion = $oDB->getOne($sql);

		switch ($currSysVersion) {
			case '':
				$this->updateTo101();
				$this->finish();
		}
	}

	/**
	 * Makes all the changes needed to upgrade to version 1.01 from version 1.00.
	 */
	public function updateTo101() {
		$myConfig  = $this->getConfig();
		$shopid = $myConfig->getShopId();
		$oDB = oxDb::getDb(true);
		$kutil = oxNew('klarnautil');

		if(!$this->oDB) {
			$this->oDB = oxDb::getDb(true);
		}
		if(!$this->shopId) {
			$myConfig = $this->getConfig();
			$this->shopId = $myConfig->getShopId();
		}
		if(!$this->kutil) {
			$this->kutil = oxNew('klarnautil');
		}

		$sql = 'ALTER TABLE klarnaconfig ADD (CURRVERSION VARCHAR(40), VENDORCOUNTRY VARCHAR(4), INVOICEFEESE DOUBLE,
					INVOICEFEENO DOUBLE, INVOICEFEEFI DOUBLE, INVOICEFEEDK DOUBLE, INVOICEFEENL DOUBLE,
					YSALARYSE DOUBLE, YSALARYNO DOUBLE, YSALARYFI DOUBLE, YSALARYDK DOUBLE, YSALARYNL DOUBLE);';
		$this->oDB->execute($sql);

		$sql = 'ALTER TABLE klarnainstall ADD ACURRENCIES TINYINT(1) NOT NULL DEFAULT 0;';
		$this->oDB->execute($sql);

		$sellTo .= '1|DE__@@1|SE__@@1|NO__@@1|FI__@@1|DK__@@1|NL__@@';
		$sql = "UPDATE klarnaconfig SET SELLTO = '$sellTo', YSALARYSE = '-1', YSALARYNO = '-1', YSALARYFI = '-1', YSALARYDK = '1', YSALARYNL = '-1' WHERE OXID = '" . $shopid . "';";
		$this->oDB->execute($sql);

		//Add the payments
		$newData .= 'kigender__@@kibirth__@@kifon__@@kimobfon__@@kiuser__@@kistreet__@@kistreetnr__@@kihouseextension__@@';
		$sql = "UPDATE oxpayments SET OXVALDESC = '$newData', OXVALDESC_1 = '$newData' WHERE OXID = 'klarnainvoice';";
		$this->oDB->execute($sql);

		$newData .= 'kppgender__@@kppbirth__@@kppfon__@@kppmobfon__@@kppuser__@@kppstreet__@@kppstreetnr__@@kppysalary__@@kpppclassid__@@kpphouseextension__@@';
		$sql = "UPDATE oxpayments SET OXVALDESC = '$newData', OXVALDESC_1 = '$newData' WHERE OXID = 'klarnapartpayment';";
		$this->oDB->execute($sql);

		$sql = "INSERT IGNORE INTO oxpayments (OXID, OXACTIVE, OXDESC, OXDESC_1, OXFROMAMOUNT, OXTOAMOUNT, OXVALDESC, OXVALDESC_1, OXCHECKED, OXLONGDESC, OXLONGDESC_1, OXSORT) VALUES
			('klarnaspecialcampaign', 1, 'Klarna special campaign', 'Klarna special campaign', 0, 1000000, 'kscgender__@@kscbirth__@@kscfon__@@kscmobfon__@@kscuser__@@kscstreet__@@kscstreetnr__@@kscysalary__@@kscpclassid__@@kschouseextension__@@', 'kscgender__@@kscbirth__@@kscfon__@@kscmobfon__@@kscuser__@@kscstreet__@@kscstreetnr__@@kscysalary__@@kscpclassid__@@kschouseextension__@@', 1, '', '', -98);";
		$this->oDB->execute($sql);

		//Add the language support
		$sql = "ALTER TABLE oxpayments ADD (OXDESC_4 VARCHAR(128), OXVALDESC_4 TEXT);"; $this->oDB->execute($sql);
		$sql = "ALTER TABLE oxpayments ADD (OXDESC_5 VARCHAR(128), OXVALDESC_5 TEXT);"; $this->oDB->execute($sql);
		$sql = "ALTER TABLE oxpayments ADD (OXDESC_6 VARCHAR(128), OXVALDESC_6 TEXT);"; $this->oDB->execute($sql);
		$sql = "ALTER TABLE oxpayments ADD (OXDESC_7 VARCHAR(128), OXVALDESC_7 TEXT);"; $this->oDB->execute($sql);
		$sql = "ALTER TABLE oxpayments ADD (OXDESC_8 VARCHAR(128), OXVALDESC_8 TEXT);"; $this->oDB->execute($sql);
		$sql = "ALTER TABLE oxpayments ADD (OXDESC_9 VARCHAR(128), OXVALDESC_9 TEXT);"; $this->oDB->execute($sql);
		$sql = "ALTER TABLE oxpayments ADD (OXDESC_10 VARCHAR(128), OXVALDESC_10 TEXT);"; $this->oDB->execute($sql);

		$tempName = 'Klarna invoice';
		$tempContent = 'kigender__@@kibirth__@@kifon__@@kimobfon__@@kiuser__@@kistreet__@@kistreetnr__@@kihouseextension__@@';
		$sql = "UPDATE oxpayments SET OXDESC_3 = '$tempName', OXVALDESC_3 = '$tempContent',
										OXDESC_4 = '$tempName', OXVALDESC_4 = '$tempContent',
										OXDESC_5 = '$tempName', OXVALDESC_5 = '$tempContent',
										OXDESC_6 = '$tempName', OXVALDESC_6 = '$tempContent',
										OXDESC_7 = '$tempName', OXVALDESC_7 = '$tempContent',
										OXDESC_8 = '$tempName', OXVALDESC_8 = '$tempContent',
										OXDESC_9 = '$tempName', OXVALDESC_9 = '$tempContent',
										OXDESC_10 = '$tempName', OXVALDESC_10 = '$tempContent'
										WHERE oxid = 'klarnainvoice';";
		$this->oDB->execute($sql);

		$tempName = 'Klarna part payment';
		$tempContent = 'kppgender__@@kppbirth__@@kppfon__@@kppmobfon__@@kppuser__@@kppstreet__@@kppstreetnr__@@kppysalary__@@kpppclassid__@@kpphouseextension__@@';
		$sql = "UPDATE oxpayments SET OXDESC_3 = '$tempName', OXVALDESC_3 = '$tempContent',
										OXDESC_4 = '$tempName', OXVALDESC_4 = '$tempContent',
										OXDESC_5 = '$tempName', OXVALDESC_5 = '$tempContent',
										OXDESC_6 = '$tempName', OXVALDESC_6 = '$tempContent',
										OXDESC_7 = '$tempName', OXVALDESC_7 = '$tempContent',
										OXDESC_8 = '$tempName', OXVALDESC_8 = '$tempContent',
										OXDESC_9 = '$tempName', OXVALDESC_9 = '$tempContent',
										OXDESC_10 = '$tempName', OXVALDESC_10 = '$tempContent'
										WHERE oxid = 'klarnapartpayment';";
		$this->oDB->execute($sql);

		$tempName = 'Klarna special campaign';
		$tempContent = 'kscgender__@@kscbirth__@@kscfon__@@kscmobfon__@@kscuser__@@kscstreet__@@kscstreetnr__@@kscysalary__@@kscpclassid__@@kschouseextension__@@';
		$sql = "UPDATE oxpayments SET OXDESC_3 = '$tempName', OXVALDESC_3 = '$tempContent',
										OXDESC_4 = '$tempName', OXVALDESC_4 = '$tempContent',
										OXDESC_5 = '$tempName', OXVALDESC_5 = '$tempContent',
										OXDESC_6 = '$tempName', OXVALDESC_6 = '$tempContent',
										OXDESC_7 = '$tempName', OXVALDESC_7 = '$tempContent',
										OXDESC_8 = '$tempName', OXVALDESC_8 = '$tempContent',
										OXDESC_9 = '$tempName', OXVALDESC_9 = '$tempContent',
										OXDESC_10 = '$tempName', OXVALDESC_10 = '$tempContent'
										WHERE oxid = 'klarnaspecialcampaign';";
		$this->oDB->execute($sql);

		//Add user groups
		$oGroups = oxNew('oxlist');
		$oGroups->init('oxgroups');
		$oGroups->selectString('SELECT OXID from oxgroups;');

		$sql = "DELETE FROM oxobject2group WHERE OXOBJECTID = 'klarnaspecialcampaign';";
		$this->oDB->execute($sql);

		$iName = $this->kutil->getIName();
		$ppName = $this->kutil->getPPName();
		$scName = $this->kutil->getSCName();
		foreach($oGroups as $item) {
			$id = $item->oxgroups__oxid->value;
			$randOne = md5(uniqid());

			$sql = "INSERT IGNORE INTO oxobject2group (OXID, OXSHOPID, OXOBJECTID, OXGROUPSID) VALUES ('$randOne', '$this->shopId', '$scName', '$id');";
			$this->oDB->execute($sql);
		}

		//Add shipping types
		$oGroups = oxNew( "oxlist" );
		$oGroups->init( 'oxdeliveryset' );
		$oGroups->selectString("SELECT OXID from oxdeliveryset;");

		$sql = "DELETE FROM oxobject2payment WHERE OXPAYMENTID = 'klarnainvoice' AND OXTYPE = 'oxdelset';";
		$this->oDB->execute($sql);
		$sql = "DELETE FROM oxobject2payment WHERE OXPAYMENTID = 'klarnapartpayment' AND OXTYPE = 'oxdelset';";
		$this->oDB->execute($sql);
		$sql = "DELETE FROM oxobject2payment WHERE OXPAYMENTID = 'klarnaspecialcampaign' AND OXTYPE = 'oxdelset';";
		$this->oDB->execute($sql);

		foreach($oGroups as $item) {
			$id = $item->oxdeliveryset__oxid->value;
			$randOne = md5(uniqid());
			$randTwo = md5(uniqid());
			$randThree = md5(uniqid());

			$sql = "INSERT IGNORE INTO oxobject2payment (OXID, OXPAYMENTID, OXOBJECTID, OXTYPE) VALUES ('$randOne', '$iName', '$id', 'oxdelset');";
			$this->oDB->execute($sql);

			$sql = "INSERT IGNORE INTO oxobject2payment (OXID, OXPAYMENTID, OXOBJECTID, OXTYPE) VALUES ('$randTwo', '$ppName', '$id', 'oxdelset');";
			$this->oDB->execute($sql);

			$sql = "INSERT IGNORE INTO oxobject2payment (OXID, OXPAYMENTID, OXOBJECTID, OXTYPE) VALUES ('$randThree', '$scName', '$id', 'oxdelset');";
			$this->oDB->execute($sql);
		}

		//Add countries
		$countries = $this->kutil->getDefaultCountries();
		foreach ($countries as $key => $value) {
			if($key == 'NO') {
				$sql = "UPDATE oxcountry SET OXACTIVE = 1, OXVATSTATUS = 1 WHERE OXISOALPHA2 = '$key';";
			} else {
				$sql = "UPDATE oxcountry SET OXACTIVE = 1 WHERE OXISOALPHA2 = '$key';";
			}
			$this->oDB->execute($sql);
		}

		$oGroups = oxNew( "oxlist" );
		$oGroups->init( 'oxcountry' );
		$oGroups->selectString("SELECT OXID from oxcountry WHERE OXACTIVE = 1;");

		$sql = "DELETE FROM oxobject2payment WHERE OXPAYMENTID = 'klarnainvoice' AND OXTYPE = 'oxcountry';";
		$this->oDB->execute($sql);
		$sql = "DELETE FROM oxobject2payment WHERE OXPAYMENTID = 'klarnapartpayment' AND OXTYPE = 'oxcountry';";
		$this->oDB->execute($sql);
		$sql = "DELETE FROM oxobject2payment WHERE OXPAYMENTID = 'klarnaspecialcampaign' AND OXTYPE = 'oxcountry';";
		$this->oDB->execute($sql);

		foreach($oGroups as $item) {
			$id = $item->oxcountry__oxid->value;
			$randOne = md5(uniqid());
			$randTwo = md5(uniqid());
			$randThree = md5(uniqid());

			$sql = "INSERT IGNORE INTO oxobject2payment (OXID, OXPAYMENTID, OXOBJECTID, OXTYPE) VALUES ('$randOne', '$iName', '$id', 'oxcountry');";
			$this->oDB->execute($sql);

			$sql = "INSERT IGNORE INTO oxobject2payment (OXID, OXPAYMENTID, OXOBJECTID, OXTYPE) VALUES ('$randTwo', '$ppName', '$id', 'oxcountry');";
			$this->oDB->execute($sql);

			$sql = "INSERT IGNORE INTO oxobject2payment (OXID, OXPAYMENTID, OXOBJECTID, OXTYPE) VALUES ('$randThree', '$scName', '$id', 'oxcountry');";
			$this->oDB->execute($sql);
		}

		$this->kutil->addNewCurrencies();
	}

	public function finish() {
		$myConfig  = $this->getConfig();
		$shopid = $myConfig->getShopId();
		$oDB = oxDb::getDb(true);
		if(!$this->kutil) {
			$this->kutil = oxNew('klarnautil');
		}

		$version = $this->kutil->getKredVersion();
		$sql = "UPDATE klarnaconfig SET CURRVERSION = '$version' WHERE OXID = '" . $shopid . "';";
		$oDB->execute($sql);

		$installer = $this->kutil->getInstallObject();
		$installer->klarnainstall__saveconfig->rawValue = 0;
		$installer->klarnainstall__acurrencies->rawValue = 1;
		$installer->klarnainstall__done->rawValue = 0;
		$installer->save();

//		$mydir = "C:/xampp/htdocs/oxid4203/tmp/";
//		$d = dir($mydir);
//		while($entry = $d->read()) {
//			if ($entry!= "." && $entry!= "..") {
//				unlink($entry);
//			}
//		}
//		$d->close();
	}
}
?>